<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Db
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * DbConnection
 */
class DbConnection extends Object
{
    const COMMON_SPACE      = 'common';

    private static $handlers       = array();

    /**
     * Singletone
     *
     * @var DbConnection
     */
    private static $instance;
    
    /**
     * Конструктор класса
     * 
     */
    private function __construct() {}

    /**
     * Get mysqli instance and connect to DB.
     *
     * @param string $space
     * @param boolean $writable
     * @return mysqli
     */
    public static function get($space, $writable)
    {
        if(!self::$instance instanceof DbConnection) {
            self::$instance = new DbConnection();
        }

        if(!array_key_exists($space, self::$handlers)) {
            $charset = 'UTF8';
            
            /** @var $servers ConfigPropery **/
            $dbspace = self::$instance->getProperty($space);
            if($writable) {
                $server = $dbspace->servers->find("server[@role = 'master']");
            } else {
                $server = $dbspace->servers->server;
            }

            $scheme = parse_url($server->dsn->toString());
            $scheme['pass'] = array_key_exists('pass', $scheme) ? $scheme['pass'] : null;
            $scheme['path'] = trim(array_key_exists('pass', $scheme) ? $scheme['path'] : null, '/');
            
            if($scheme['query']) {
                parse_str($scheme['query'], $query);
                if(array_key_exists('charset', $query)) {
                    $charset = $query['charset'];
                }
            }
            
            $mysqli = new mysqli($scheme['host'], $scheme['user'], $scheme['pass'], $scheme['path']);
            
            if(mysqli_connect_errno() || !$mysqli instanceof mysqli)
            {
                throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
            }
            
            $mysqli->set_charset($charset);
            self::$handlers[$space] = $mysqli;
        }

        self::$handlers[$space]->autocommit(true);
        return self::$handlers[$space];
    }
    
    public static function init($namespace)
    {
        if(!self::$instance instanceof DbConnection) {
            self::$instance = new DbConnection();
        }
        
        self::$instance->setNamespace($namespace);
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>
